<template>
  <el-card header="年检结果">
    <div class="app-container">
      <MForm :fields="fields" :modelValue="modelValue" @submit="search" @cancel="search">
        <template #extra>
          <el-button type="warning" @click="handleNoCheck">查询未参检</el-button>
          <el-button type="warning" @click="handleCompletedTime">办结时间</el-button>
        </template>
      </MForm>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="60" />
        <el-table-column label="组织单位" prop="data2" width="280" :show-overflow-tooltip="true">
          <template v-slot="scope">
            <div style="height: 28px; line-height: 28px">
              <span>名称：{{ scope.row.organizationBaseName }}</span>
            </div>
            <div style="height: 28px; line-height: 28px">
              <span>编码：{{ scope.row.creditCode }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="主管部门" align="center" prop="supervisoryUnit" width="220" :show-overflow-tooltip="true"/>
        <el-table-column label="年检年份" align="center" prop="examineYear" width="100"/>
        <el-table-column label="组织类别" prop="organizationType" width="110" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.organizationType == 1 ? 'warning' : ''">
              <span class="tag">{{
                scope.row.organizationType == 1 ? '社团' : '民非'
              }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="法定代表人/负责人" align="center" prop="legalRepresentativeName" width="160" />
        <el-table-column label="办结时间" align="center" prop="approveTime" width="180" />
        <el-table-column label="办结时长" align="center" prop="completionAvgTime" width="180" />
        <el-table-column label="年检时长" align="center" prop="completionAvgCountTime" width="180" />
        <el-table-column label="年检结果" align="center" prop="approveStatus" width="180">
          <template v-slot="scope">
            <div v-if="scope.row.approveStatus && scope.row.approveStatus > 0">
              <el-tag style="cursor: pointer;" :type="checkRArr[scope.row.approveStatus].type"
                @click="handleHistory(scope.row)">
                <span class="tag">{{ checkRArr[scope.row.approveStatus].txt }}</span>
              </el-tag>
              <el-button size="default" type="text" @click="handleReason(scope.row)" style="margin-left: 10px">查看详情
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="230" fixed="right">
          <template v-slot="scope">
            <el-button size="mini" type="text" :icon="Document" @click="handleCheck(scope.row)">查看</el-button>
<!--            <el-button size="mini" type="text" :icon="Document" @click="PreviewPDF(scope.row)">预览PDF</el-button>-->
            <el-button size="mini" :loading="exportLoadding" type="text" :icon="Download" @click="downloadFile(scope.row)">导出资料</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pageInfo-box">
        <el-pagination v-model:current-page="params.pageNum" :page-sizes="[100, 200, 300, 400]" background
          layout="total, sizes, prev, pager, next, jumper" :total="total" @current-change="search" />
      </div>
    </div>
  </el-card>
  <el-dialog title="年检详情" v-model="dialogDetail" width="1000px" top="4vh" append-to-body>
    <p>
      <span>组织名称：</span>
      <span>{{ reasonDetail.organizationBaseName }}</span>
    </p>
    <p>
      <span>年检结果：</span>
      <el-tag :type="checkRArr[reasonDetail.approveStatus].type">
        <span class="tag">{{ checkRArr[reasonDetail.approveStatus].txt }}</span>
      </el-tag>
    </p>
    <div>
      <p class="title">审核记录</p>
      <table class="m-table">
        <tr>
          <td>序号</td>
          <td>审核人</td>
          <td>审核步骤</td>
          <td>审核人意见</td>
          <td>审核结果</td>
          <td>操作时间</td>
          <td>签字确认</td>
        </tr>
        <tr v-for="(item, index) in checkRecordList">
          <td>{{ index + 1 }}</td>
          <td>{{ cStepList[index] }}</td>
          <td>{{ item.approveUserName }}</td>
          <td>{{ item.approveDescription }}</td>
          <td :class="['td-result', item.approveStatus && checkRArr[item.approveStatus].class]">
            {{ index > 2 ? (item.approveStatus && checkRArr[item.approveStatus].txt) : '' }}</td>
          <td>{{ item.createdTs }}</td>
          <td>{{ item.signUrl }}</td>
        </tr>
      </table>
    </div>
  </el-dialog>
  <el-dialog destroy-on-close v-model="dialogCheckVisible" title="年检审核" width="95%" top="3vh">
    <checkST :showBtn="false" v-if="isSt" :currentRow="chooseRow">
    </checkST>
    <checkMF v-else :showBtn="false" :currentRow="chooseRow">
    </checkMF>
  </el-dialog>
  <!-- <div style="height: 1px;overflow: hidden;" v-if="pdfMack"> -->
  <el-dialog destroy-on-close v-model="pdfMack" title="年检详情" width="75%" top="3vh">
    <printIndexST v-if="isSt" :currentRow="chooseRow" ref="RefChild">
    </printIndexST>
    <printIndexMF v-else :currentRow="chooseRow" ref="RefChild">
    </printIndexMF>
  </el-dialog>

  <el-dialog destroy-on-close v-model="dialogHisvisible" width="600px" style="margin-top: 10px;" :show-close="false">
    <yearlyInfo :yearApprove="yearApprove" :userName="orgName"></yearlyInfo>
  </el-dialog>

  <el-dialog destroy-on-close v-model="dialogNoCvisible" title="未参检" width="1600" top="3vh">
    <noCheck></noCheck>
  </el-dialog>
  <el-dialog destroy-on-close v-model="dialogCTimevisible" title="平均办结时间" width="1600" top="3vh">
    <comTime></comTime>
  </el-dialog>
  <!-- </div> -->
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { fields, modelValue } from './config'
import { checkResult, getCheckStep } from '@/api/yearCheck/index'
import { ElLoading } from 'element-plus'
import { Menu, Download, Document } from '@element-plus/icons-vue'
import checkST from '@/views/yearCheck/wCheck/components/checkST/checkST.vue'
import checkMF from '@/views/yearCheck/wCheck/components/checkMF/checkMF.vue'
import printIndexST from '@/views/yearCheck/checkResult/printIndexST.vue'
import printIndexMF from '@/views/yearCheck/checkResult/printIndexMF.vue'
import noCheck from '@/views/yearCheck/checkResult/components/noCheck/index.vue'
import comTime from '@/views/yearCheck/checkResult/components/comTime/index.vue'
import yearlyInfo from '@/views/yearCheck/ykb/other/yearlyInfo.vue'
import { wrapperLoadViteEnv } from '~/build/utils'
import db from '@/storage'
import { saveAs } from 'file-saver'
import axios from 'axios'

let cStepList = ref(['提交申请', '校对检查', '主管单位管理员指派', '主管单位经办人审核', '主管单位分管领导审核', '登记单位审核', '最终结果'])
const exportLoadding = ref(false)
const dialogDetail = ref(false)
const dialogCheckVisible = ref(false) //审核
const dialogHisvisible = ref(false) //审核
const dialogNoCvisible = ref(false) //未参检列表
const dialogCTimevisible = ref(false) //办结时间
const pdfMack = ref(false) //审核
const total = ref()
const RefChild = ref()
const isSt = ref(true)
const chooseRow = ref({})
const yearApprove = ref({})
const orgName = ref('')
const tableData = ref([])
const checkRecordList = ref([])
// const modelValue = ref()
const reasonDetail = ref({
  approveStatus: 1,
  organizationBaseName: 1,
})

const checkRArr = ref(
  [
    {
      txt: '',
      type: '',
      class: ''
    }, {
      txt: '合格',
      type: 'success',
      class: 'pass'
    },
    {
      txt: '基本合格',
      type: 'warning',
      class: 'base-pass'
    },
    {
      txt: '不合格',
      type: 'danger',
      class: 'no-pass'
    },
    {
      txt: '未年检',
      type: 'info'
    }
  ])
// 搜索
const params = ref<any>({
  pageSize: 10,
  pageNum: 1,
})

const search = (data: any) => {
  params.value = {
    ...params.value,
    ...data
  }
  checkResult(params.value).then(res => {
    tableData.value = res.rows
    total.value = res.total
  })
}
search(modelValue)


const handleReason = (row) => {
  reasonDetail.value = { ...row }
  dialogDetail.value = true
  getCStepList(row.id)
}

//历史年检结果
const handleHistory = (row) => {
  yearApprove.value = Object.assign({}, row)
  orgName.value = row.organizationBaseName
  dialogHisvisible.value = true
}

const handleCheck = (row) => {
  // localStorage.setItem('fMOrgId', row.creditCode)
  // localStorage.setItem('fMExamineYear', row.examineYear)
  isSt.value = row.organizationType == 1 ? true : false;
  chooseRow.value = Object.assign({}, row)
  dialogCheckVisible.value = true
}

const handleNoCheck = (row) => {
  dialogNoCvisible.value = true
}

const handleCompletedTime = (row) => {
  dialogCTimevisible.value = true
}
//预览
const PreviewPDF = (row) => {
  // const loading = ElLoading.service({
  //   lock: true,
  //   text: '下载中...',
  //   background: 'rgba(0, 0, 0, 0.2)'
  // })
  isSt.value = row.organizationType == 1 ? true : false;
  pdfMack.value = true
  chooseRow.value = Object.assign({}, row)
  // setTimeout(() => {
  //   // window.location.href = 'https://zgdxyyfgs.com:8201/file/society-org/云阳县篮球协会{{ myYears.currentYear}}年社会团体年检信息.pdf'
  //   window.open('https://zgdxyyfgs.com:8201/file/society-org/云阳县篮球协会{{ myYears.currentYear}}年社会团体年检信息.pdf')
  //   loading.close()
  // }, 2000)
}

//下载
const downloadFile = (row) => {
  let param = {creditCode:row.creditCode,examineYear:row.examineYear};
  const viteEnv = wrapperLoadViteEnv(import.meta.env)
  exportLoadding.value = true;
  if(row.organizationType == 1){
    console.log(viteEnv.VITE_BASE_URL_API)
    axios({
      method: 'post',
      url: viteEnv.VITE_BASE_URL_API + 'hbsys-system/inspectionResults/associationExport',
      headers: {
        Authorization: 'Bearer ' + db.get('token') // 如果需要身份验证，可以在这里添加token
      },
      responseType: 'blob',
      params: param
    }).then((res) => {
      console.log(res)
      exportLoadding.value = false;
      if (res.data.size == 0) {
        return
      }
      const blob = new Blob([res.data], { type: 'application/pdf' }) // 创建Blob对象
      const pdfUrl = URL.createObjectURL(blob) // 创建Blob URL
      saveAs(pdfUrl, row.examineYear + '年检资料.pdf')
    }, (err) => {
      console.log(err)
      exportLoadding.value = false;
    })
  }else {
    axios({
      method: 'post',
      url: viteEnv.VITE_BASE_URL_API + 'hbsys-system/inspectionResults/minFeiExport',
      headers: {
        Authorization: 'Bearer ' + db.get('token') // 如果需要身份验证，可以在这里添加token
      },
      responseType: 'blob',
      params: param
    }).then((res) => {
      console.log(res)
      exportLoadding.value = false;
      if (res.data.size == 0) {
        return
      }
      const blob = new Blob([res.data], { type: 'application/pdf' }) // 创建Blob对象
      const pdfUrl = URL.createObjectURL(blob) // 创建Blob URL
      saveAs(pdfUrl, row.examineYear + '年检资料.pdf')
    }, (err) => {
      console.log(err)
      exportLoadding.value = false;
    })
  }
  //url是pdf链接
  // const url = 'https://zgdxyyfgs.com:8201/file/society-org/云阳县篮球协会{{ myYears.currentYear}}年社会团体年检信息.pdf'
  // axios
  //   .get(url, {
  //     responseType: "arraybuffer",
  //   })
  //   .then((res: any) => {
  //     let fileName = '云阳县篮球协会{{ myYears.currentYear}}年社会团体年检信息.pdf'
  //     download(res, fileName);
  //   });
  // 获取子组件的引用
  // isSt.value = row.organizationType == 1 ? true : false;
  // chooseRow.value = Object.assign({}, row)
  // pdfMack.value = true
  // setTimeout(() => {
  //   RefChild.value.handleDownload()
  // }, 3000)
};
const download = (res, filename) => {
  // 创建blob对象，解析流数据
  const blob = new Blob([res.data]);
  const a = document.createElement("a");
  // 兼容webkix浏览器，处理webkit浏览器中href自动添加blob前缀，默认在浏览器打开而不是下载
  const URL = window.URL || window.webkitURL;
  // 根据解析后的blob对象创建URL 对象
  const herf = URL.createObjectURL(blob);
  // 下载链接
  a.href = herf;
  // 下载文件名,如果后端没有返回，可以自己写a.download = '文件.pdf'
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  // 在内存中移除URL 对象
  window.URL.revokeObjectURL(herf);
}


const getCStepList = (id) => {
  getCheckStep(id).then(res => {
    checkRecordList.value = res.data;
    console.log(checkRecordList.value)
  })
}
</script>
<style scoped lang="scss">
.pageInfo-box {
  display: flex;
  justify-content: right;
  padding-top: 30px;
}

.title {
  height: 40px;
  line-height: 40px;
  font-size: 16px;
  position: relative;
  padding-left: 15px;

  &:before {
    width: 7px;
    height: 19px;
    position: absolute;
    content: "";
    background-color: #1c85ff;
    left: 0;
    top: 12px;
    border-radius: 3px;
  }
}

table.m-table {
  border-spacing: 0px;
  width: 100%;
  border-top: 1px solid #999;
  border-left: 1px solid #999;
  color: #000;

  thead {
    background: #f0f7fc;
    color: rgb(37, 43, 53);

    th {
      border-right: 1px solid #999;
      border-bottom: 1px solid #999;
      text-align: center;
      height: 32px;
    }
  }

  td {
    height: 32px;
    border-right: 1px solid #999;
    border-bottom: 1px solid #999;
    text-align: center;

    &.td-head {
      background: #f0f7fc;
    }
  }
}

.td-result {
  color: #67c23a;

  &.base-pass {
    color: #e9a586;
  }

  &.no-pass {
    color: #e22c4a;
  }
}
</style>
